<template>
  <div>
    <SearchForm @search="getTableData" @reset="resetSearch">
      <el-col :span="8" :xs="24" v-if="$permiss[1276]">
        <el-form-item :label="$t('所属租户')">
          <el-select v-model="page.adminUserId" @change="tenantChange" style="width: 100%" clearable>
            <el-option v-for="item in tenantList" :key="item.adminUserId"
                       :label="item.adminName"
                       :value="item.adminUserId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('订单编号')">
          <el-input v-model="page.loanRecordId"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('用户姓名')">
          <el-input v-model="page.userName"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('手机号码')">
          <el-input v-model="page.phone"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('身份证')">
          <el-input v-model="page.idCard"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('展期状态')">
          <el-select v-model="page.status" style="width: 100%;" clearable>
            <el-option v-for="item in extendStatus" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-if="$permiss[1277]">
        <el-form-item :label="$t('APP名称')">
          <el-select style="width: 100%" v-model="page.productName" clearable>
            <el-option v-for="item in productList" :key="item.productId" :label="item.appName"
                       :value="item.productName"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('交易流水')">
          <el-input v-model="page.transFlow"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('还款渠道')">
          <el-select v-model="page.channelName" style="width: 100%" clearable>
            <el-option v-for="item in channelList" :key="item" :value="item" :label="item"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('还款时间')">
          <el-date-picker
              v-model="page.repaymentTime"
              style="width: 100%"
              type="daterange"
              unlink-panels
              range-separator="~"
              value-format="yyyy-MM-dd"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>
    <el-card shadow="never" style="margin-top: 10px">
      <div style="display:flex; align-items: center;margin-bottom: 10px;justify-content: space-between">
        <el-link :underline="false" type="primary" style="margin-bottom: 10px"> {{ $t('已还手续费') }} :{{ amountTotal }}
        </el-link>
        <el-button
            type="primary"
            @click="exportsExcel"
            :loading="exportsLoading"
        >{{ $t("导出") }}
        </el-button>
      </div>
      <Table :table-data="tableData" :table-column="tableColumn" :page="page"
             @handleSizeChange="handleSizeChange"
             @handleCurrentChange="handleCurrentChange"
             :loading="loading"
      >
        <template slot="status" slot-scope="{row}">
          {{ extendStatus.find(item => item.value === row.status).label }}
        </template>
        <template slot="handle" slot-scope="{row}">
          <el-button type="text" v-show="$permiss[1595] && (row.status === 1|| row.status === 0)"
                     @click="rollOverBack(row)">{{ $t('回退') }}
          </el-button>
        </template>
      </Table>
    </el-card>
  </div>
</template>
<script>
import {dateFormatSection} from "@/utils/tools";
import {
  selectRollDetailPage,
  selectDetailPageExport,
  rollDetailTotalAmount,
  rollOverBack,
} from '@/api/finance'
import {selectProduct, selectTenant} from "@/api/system";
import {export_json_to_excel} from "@/utils/exportExcel";

export default {
  name: "extendCollectionDetails",
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tenantList: [],
      productList: [],
      extendStatus: [
        {label: this.$t('展期中'), value: 0},
        {label: this.$t('展期成功'), value: 1},
        {label: this.$t('展期失败'), value: 2},
        {label: this.$t('展期退回'), value: 3},
      ],
      tableData: [],
      tableColumn: [
        {label: this.$t('订单编号'), prop: 'loanRecordId', fixed: 'left', minWidth: 150},
        {label: this.$t('用户姓名'), prop: 'userName', minWidth: 100},
        {label: this.$t('手机号码'), prop: 'phone', minWidth: 100},
        {label: this.$t('身份证'), prop: 'idCard', minWidth: 100},
        {label: this.$t('应还时间'), prop: 'shouldRefundDate', minWidth: 150},
        {label: this.$t('应支付展期手续费'), prop: 'shouldRollAmount', minWidth: 150},
        {label: this.$t('本次已还手续费'), prop: 'actualRollAmount', minWidth: 150},
        {label: this.$t('展期状态'), prop: 'status', slot: 'status', minWidth: 100},
        {label: this.$t('交易流水'), prop: 'transFlow', minWidth: 100},
        {label: this.$t('还款渠道'), prop: 'channelName', minWidth: 100},
        {label: this.$t('APP名称'), prop: 'appName', minWidth: 100},
        {label: this.$t('回款时间'), prop: 'createTime', minWidth: 150},
        {label: this.$t('所属租户'), prop: 'adminUserName', minWidth: 100, isHide: !this.$permiss[1276]},
        {label: this.$t('操作'), slot: 'handle', fixed: 'right', isHide: !this.$permiss[1595]},
      ],
      amountTotal: 0,
      loading: false,
      exportsLoading: false
    }
  },
  computed: {
    channelList() {
      return process.env.VUE_APP_REGION === 'moxige' ? ["PANDAPAY", "MXFLINPAY", "STP",] : ['BAOKIM', 'FUNPAY']
    }
  },
  mounted() {
    this.getSelect()
    this.getTableData()
  },
  methods: {
    async getTableData() {
      this.loading = true
      const [createTimeStart, createTimeEnd] = dateFormatSection(this.page.repaymentTime || [])
      const params = {
        ...this.page,
        createTimeStart, createTimeEnd
      }
      delete params.repaymentTime
      this.getTotal(params)
      const res = await selectRollDetailPage(params)
      if (res.code === 1) {
        const {list, total} = res.data
        this.tableData = list
        this.page.total = total
        this.loading = false
      } else {
        this.loading = false
      }
    },
    async getTotal(params) {
      const res = await rollDetailTotalAmount(params)
      if (res.code === 1) {
        this.amountTotal = res.data || 0
      }
    },
    resetSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    // 展期退回
    rollOverBack(row) {
      this.$confirm(this.$t("为避免造成损失，请确认是否进行该操作") + '?', this.$t("提示"), {
        type: "warning",
      }).then(async () => {
        const formData = new FormData()
        formData.append('id', row.id)
        const res = await rollOverBack(formData)
        if (res.code === 1) {
          this.$message.success(this.$t('操作成功'))
          this.getTableData()
        }
      }).catch(() => {
      });
    },
    tenantChange(value) {
      selectProduct({adminUserId: value}).then(res => {
        this.productList = res.data
        this.$set(this.page, 'productName', null)
      })
    },
    getSelect() {
      selectProduct().then(res => {
        this.productList = res.data
      })
      selectTenant().then(res => {
        this.tenantList = res.data
      })
    },
    async exportsExcel() {
      this.exportsLoading = true;
      const [createTimeStart, createTimeEnd] = dateFormatSection(this.page.repaymentTime || [])
      const params = {
        ...this.page,
        createTimeStart, createTimeEnd
      }
      delete params.repaymentTime
      const res = await selectDetailPageExport(params);
      if (res.code === 1) {
        const headerData = [...this.tableColumn].filter(item => {
          const result = res.data.filter(i => {
            //过滤没有权限的字段
            return typeof i[item.prop] !== "undefined"
          })
          return result.length !== 0
        })
        const column = headerData.map(item => item.label)
        const filterVal = headerData.map(item => item.prop)
        const list = [...res.data].map((item) => {
          return item;
        }).map((v) => filterVal.map((j) => v[j]));
        const fileName = this.$t("展期回款列表");
        export_json_to_excel({
          header: column,
          data: list,
          filename: fileName,
        });
        this.exportsLoading = false;
      } else {
        this.exportsLoading = false;
      }
    }
  }
}
</script>

<style scoped>

</style>
